<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>用户管理系统</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            padding: 20px;
        }

        .container {
            max-width: 1200px;
            margin: 0 auto;
            background: white;
            border-radius: 15px;
            box-shadow: 0 20px 40px rgba(0,0,0,0.1);
            overflow: hidden;
        }

        .header {
            background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
            color: white;
            padding: 30px;
            text-align: center;
        }

        .header h1 {
            font-size: 2.5em;
            margin-bottom: 10px;
            font-weight: 300;
        }

        .header p {
            font-size: 1.1em;
            opacity: 0.9;
        }

        .content {
            padding: 30px;
        }

        .form-section {
            background: #f8f9fa;
            padding: 25px;
            border-radius: 10px;
            margin-bottom: 30px;
            border: 1px solid #e9ecef;
        }

        .form-section h2 {
            color: #495057;
            margin-bottom: 20px;
            font-size: 1.5em;
            border-bottom: 2px solid #4facfe;
            padding-bottom: 10px;
        }

        .form-group {
            margin-bottom: 20px;
        }

        .form-group label {
            display: block;
            margin-bottom: 8px;
            color: #495057;
            font-weight: 500;
        }

        .form-group input {
            width: 100%;
            padding: 12px 15px;
            border: 2px solid #e9ecef;
            border-radius: 8px;
            font-size: 16px;
            transition: border-color 0.3s ease;
        }

        .form-group input:focus {
            outline: none;
            border-color: #4facfe;
            box-shadow: 0 0 0 3px rgba(79, 172, 254, 0.1);
        }

        .btn {
            padding: 12px 25px;
            border: none;
            border-radius: 8px;
            font-size: 16px;
            font-weight: 500;
            cursor: pointer;
            transition: all 0.3s ease;
            margin-right: 10px;
            margin-bottom: 10px;
        }

        .btn-primary {
            background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
            color: white;
        }

        .btn-primary:hover {
            transform: translateY(-2px);
            box-shadow: 0 5px 15px rgba(79, 172, 254, 0.4);
        }

        .btn-success {
            background: linear-gradient(135deg, #43e97b 0%, #38f9d7 100%);
            color: white;
        }

        .btn-success:hover {
            transform: translateY(-2px);
            box-shadow: 0 5px 15px rgba(67, 233, 123, 0.4);
        }

        .btn-warning {
            background: linear-gradient(135deg, #fa709a 0%, #fee140 100%);
            color: white;
        }

        .btn-warning:hover {
            transform: translateY(-2px);
            box-shadow: 0 5px 15px rgba(250, 112, 154, 0.4);
        }

        .btn-danger {
            background: linear-gradient(135deg, #ff6b6b 0%, #ee5a24 100%);
            color: white;
        }

        .btn-danger:hover {
            transform: translateY(-2px);
            box-shadow: 0 5px 15px rgba(255, 107, 107, 0.4);
        }

        .table-container {
            background: white;
            border-radius: 10px;
            overflow: hidden;
            box-shadow: 0 5px 15px rgba(0,0,0,0.08);
        }

        .table-header {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 20px;
            text-align: center;
        }

        .table-header h2 {
            margin: 0;
            font-size: 1.8em;
            font-weight: 300;
        }

        table {
            width: 100%;
            border-collapse: collapse;
            background: white;
        }

        th, td {
            padding: 15px;
            text-align: left;
            border-bottom: 1px solid #e9ecef;
        }

        th {
            background: #f8f9fa;
            color: #495057;
            font-weight: 600;
            font-size: 14px;
            text-transform: uppercase;
            letter-spacing: 0.5px;
        }

        tr:hover {
            background: #f8f9fa;
        }

        .status {
            padding: 5px 10px;
            border-radius: 20px;
            font-size: 12px;
            font-weight: 500;
            text-transform: uppercase;
        }

        .status.success {
            background: #d4edda;
            color: #155724;
        }

        .status.error {
            background: #f8d7da;
            color: #721c24;
        }

        .loading {
            text-align: center;
            padding: 20px;
            color: #6c757d;
        }

        .error-message {
            background: #f8d7da;
            color: #721c24;
            padding: 15px;
            border-radius: 8px;
            margin-bottom: 20px;
            border: 1px solid #f5c6cb;
        }

        .success-message {
            background: #d4edda;
            color: #155724;
            padding: 15px;
            border-radius: 8px;
            margin-bottom: 20px;
            border: 1px solid #c3e6cb;
        }

        /* 统计按钮样式 */
        .stats-btn {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            border: none;
            padding: 6px 12px;
            border-radius: 6px;
            cursor: pointer;
            font-size: 12px;
            margin-left: 8px;
            transition: all 0.3s ease;
        }

        .stats-btn:hover {
            transform: translateY(-2px);
            box-shadow: 0 4px 8px rgba(0,0,0,0.2);
        }

        /* 统计模态框样式 */
        .stats-modal {
            display: none;
            position: fixed;
            z-index: 1000;
            left: 0;
            top: 0;
            width: 100%;
            height: 100%;
            background-color: rgba(0,0,0,0.5);
        }

        .stats-modal-content {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            margin: 5% auto;
            padding: 0;
            border-radius: 15px;
            width: 80%;
            max-width: 800px;
            box-shadow: 0 10px 30px rgba(0,0,0,0.3);
            animation: modalSlideIn 0.3s ease;
        }

        @keyframes modalSlideIn {
            from {
                transform: translateY(-50px);
                opacity: 0;
            }
            to {
                transform: translateY(0);
                opacity: 1;
            }
        }

        .stats-modal-header {
            background: rgba(255,255,255,0.1);
            padding: 20px;
            border-radius: 15px 15px 0 0;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }

        .stats-modal-header h2 {
            color: white;
            margin: 0;
            font-size: 1.5em;
        }

        .stats-modal-close {
            color: white;
            font-size: 28px;
            font-weight: bold;
            cursor: pointer;
            transition: all 0.3s ease;
        }

        .stats-modal-close:hover {
            transform: scale(1.2);
        }

        .stats-modal-body {
            background: white;
            padding: 30px;
            border-radius: 0 0 15px 15px;
        }

        .stats-summary {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
            gap: 20px;
            margin-bottom: 30px;
        }

        .stats-card {
            background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
            color: white;
            padding: 20px;
            border-radius: 12px;
            text-align: center;
            box-shadow: 0 4px 15px rgba(0,0,0,0.1);
        }

        .stats-card h3 {
            margin: 0 0 10px 0;
            font-size: 1.2em;
        }

        .stats-card .value {
            font-size: 2em;
            font-weight: bold;
            margin: 10px 0;
        }

        .stats-card .unit {
            font-size: 0.9em;
            opacity: 0.8;
        }

        .stats-chart {
            background: #f8f9fa;
            padding: 20px;
            border-radius: 12px;
            margin-bottom: 20px;
        }

        .stats-chart h3 {
            margin: 0 0 15px 0;
            color: #333;
        }

        .stats-table {
            width: 100%;
            border-collapse: collapse;
            margin-top: 15px;
        }

        .stats-table th,
        .stats-table td {
            padding: 12px;
            text-align: left;
            border-bottom: 1px solid #ddd;
        }

        .stats-table th {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
        }

        .stats-table tr:hover {
            background-color: #f5f5f5;
        }

        .stats-loading {
            text-align: center;
            padding: 40px;
            color: #666;
        }

        .stats-error {
            background: #f8d7da;
            color: #721c24;
            padding: 15px;
            border-radius: 8px;
            margin-bottom: 20px;
        }

        /* 全局统计卡片样式 */
        .global-stats-section {
            background: #f8f9fa;
            padding: 25px;
            border-radius: 10px;
            margin-bottom: 30px;
            border: 1px solid #e9ecef;
            box-shadow: inset 0 0 10px rgba(0,0,0,0.05);
        }

        .global-stats-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
            gap: 20px;
            margin-bottom: 20px;
        }

        .global-stats-card {
            background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
            color: white;
            padding: 20px;
            border-radius: 12px;
            display: flex;
            align-items: center;
            box-shadow: 0 4px 15px rgba(0,0,0,0.1);
            transition: transform 0.3s ease;
        }

        .global-stats-card:hover {
            transform: translateY(-3px);
            box-shadow: 0 6px 20px rgba(0,0,0,0.15);
        }

        .global-stats-icon {
            font-size: 3em;
            margin-right: 15px;
            color: rgba(255,255,255,0.9);
        }

        .global-stats-content h4 {
            color: rgba(255,255,255,0.9);
            margin-bottom: 10px;
            font-size: 1.1em;
        }

        .global-stats-values {
            display: flex;
            justify-content: space-around;
            flex-wrap: wrap;
        }

        .global-stats-item {
            text-align: center;
            margin: 5px 10px;
        }

        .global-stats-item .label {
            font-size: 0.8em;
            opacity: 0.8;
            display: block;
            margin-bottom: 3px;
        }

        .global-stats-item .value {
            font-size: 1.8em;
            font-weight: bold;
            color: white;
        }

        .global-stats-item .unit {
            font-size: 0.7em;
            opacity: 0.7;
        }

        .search-section {
            margin-bottom: 20px;
        }

        .search-input {
            width: 300px;
            padding: 10px 15px;
            border: 2px solid #e9ecef;
            border-radius: 8px;
            font-size: 14px;
            margin-right: 10px;
        }

        .search-input:focus {
            outline: none;
            border-color: #4facfe;
        }

        @media (max-width: 768px) {
            .container {
                margin: 10px;
                border-radius: 10px;
            }

            .header {
                padding: 20px;
            }

            .header h1 {
                font-size: 2em;
            }

            .content {
                padding: 20px;
            }

            .btn {
                width: 100%;
                margin-bottom: 10px;
            }

            .search-input {
                width: 100%;
                margin-bottom: 10px;
            }

            table {
                font-size: 14px;
            }

            th, td {
                padding: 10px 8px;
            }
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="header">
            <h1>用户管理系统</h1>
            <p>FastAPI 用户管理界面</p>
        </div>

        <div class="content">
            <!-- 用户注册表单 -->
            <div class="form-section">
                <h2>用户注册</h2>
                <div class="form-group">
                    <label for="username">用户名:</label>
                    <input type="text" id="username" placeholder="请输入用户名">
                </div>
                <div class="form-group">
                    <label for="phone">手机号:</label>
                    <input type="tel" id="phone" placeholder="请输入手机号">
                </div>
                <div class="form-group">
                    <label for="email">邮箱:</label>
                    <input type="email" id="email" placeholder="请输入邮箱">
                </div>
                <div class="form-group">
                    <label for="password">密码:</label>
                    <input type="password" id="password" placeholder="请输入密码">
                </div>
                <button class="btn btn-primary" onclick="registerUser()">注册用户</button>
            </div>

            <!-- 用户登录表单 -->
            <div class="form-section">
                <h2>用户登录</h2>
                <div class="form-group">
                    <label for="loginUsername">用户名:</label>
                    <input type="text" id="loginUsername" placeholder="请输入用户名">
                </div>
                <div class="form-group">
                    <label for="loginPassword">密码:</label>
                    <input type="password" id="loginPassword" placeholder="请输入密码">
                </div>
                <button class="btn btn-success" onclick="loginUser()">登录</button>
            </div>

            <!-- 用户管理 -->
            <div class="form-section">
                <h2>用户管理</h2>
                <div class="form-group">
                    <label for="userId">用户ID:</label>
                    <input type="number" id="userId" placeholder="请输入用户ID">
                </div>
                <div class="form-group">
                    <label for="newPhone">新手机号:</label>
                    <input type="tel" id="newPhone" placeholder="请输入新手机号">
                </div>
                <div class="form-group">
                    <label for="newEmail">新邮箱:</label>
                    <input type="email" id="newEmail" placeholder="请输入新邮箱">
                </div>
                <button class="btn btn-warning" onclick="updateUser()">更新用户</button>
                <button class="btn btn-danger" onclick="deleteUser()">删除用户</button>
            </div>

            <!-- 搜索和用户列表 -->
            <div class="table-container">
                <div class="table-header">
                    <h2>用户列表</h2>
                </div>
                <div style="padding: 20px;">
                    <!-- 全局统计卡片 -->
                    <div class="global-stats-section">
                        <h3 style="margin-bottom: 15px; color: #333; font-size: 1.3em;">📊 全局使用统计</h3>
                        <div class="global-stats-grid">
                            <div class="global-stats-card">
                                <div class="global-stats-icon">📅</div>
                                <div class="global-stats-content">
                                    <h4>今日总计</h4>
                                    <div class="global-stats-values">
                                        <div class="global-stats-item">
                                            <span class="label">TTS:</span>
                                            <span class="value" id="todayTotalTTS">加载中...</span>
                                            <span class="unit">字符</span>
                                        </div>
                                        <div class="global-stats-item">
                                            <span class="label">ASR:</span>
                                            <span class="value" id="todayTotalASR">加载中...</span>
                                            <span class="unit">秒</span>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            <div class="global-stats-card">
                                <div class="global-stats-icon">📊</div>
                                <div class="global-stats-content">
                                    <h4>本月总计</h4>
                                    <div class="global-stats-values">
                                        <div class="global-stats-item">
                                            <span class="label">TTS:</span>
                                            <span class="value" id="monthTotalTTS">加载中...</span>
                                            <span class="unit">字符</span>
                                        </div>
                                        <div class="global-stats-item">
                                            <span class="label">ASR:</span>
                                            <span class="value" id="monthTotalASR">加载中...</span>
                                            <span class="unit">秒</span>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            <div class="global-stats-card">
                                <div class="global-stats-icon">🏆</div>
                                <div class="global-stats-content">
                                    <h4>历史总计</h4>
                                    <div class="global-stats-values">
                                        <div class="global-stats-item">
                                            <span class="label">TTS:</span>
                                            <span class="value" id="allTotalTTS">加载中...</span>
                                            <span class="unit">字符</span>
                                        </div>
                                        <div class="global-stats-item">
                                            <span class="label">ASR:</span>
                                            <span class="value" id="allTotalASR">加载中...</span>
                                            <span class="unit">秒</span>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <button class="btn btn-primary" onclick="refreshGlobalStats()" style="margin-top: 15px;">
                            🔄 刷新统计
                        </button>
                    </div>
                    
                    <div class="search-section">
                        <input type="text" class="search-input" id="searchInput" placeholder="搜索用户...">
                        <button class="btn btn-primary" onclick="searchUsers()">搜索</button>
                        <button class="btn btn-success" onclick="loadUsers()">刷新列表</button>
                    </div>
                    <div id="message"></div>
                    <div id="userTable"></div>
                </div>
            </div>
        </div>
    </div>

    <!-- 用户统计模态框 -->
    <div id="statsModal" class="stats-modal">
        <div class="stats-modal-content">
            <div class="stats-modal-header">
                <h2 id="statsModalTitle">用户数据统计</h2>
                <span class="stats-modal-close" onclick="closeStatsModal()">&times;</span>
            </div>
            <div class="stats-modal-body">
                <div id="statsContent">
                    <!-- 统计内容将在这里动态加载 -->
                </div>
            </div>
        </div>
    </div>

    <script>
        const API_BASE = 'http://127.0.0.1:8000/v1';

        // 显示消息
        function showMessage(message, type = 'success') {
            const messageDiv = document.getElementById('message');
            messageDiv.innerHTML = `<div class="${type}-message">${message}</div>`;
            setTimeout(() => {
                messageDiv.innerHTML = '';
            }, 5000);
        }

        // 用户注册
        async function registerUser() {
            const username = document.getElementById('username').value;
            const phone = document.getElementById('phone').value;
            const email = document.getElementById('email').value;
            const password = document.getElementById('password').value;

            if (!username || !phone || !email || !password) {
                showMessage('请填写所有字段', 'error');
                return;
            }

            try {
                const response = await fetch(`${API_BASE}/UserRegister`, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify({
                        username,
                        phone,
                        email,
                        password
                    })
                });

                const data = await response.json();

                if (response.ok) {
                    showMessage('用户注册成功！');
                    clearForm('register');
                    loadUsers();
                } else {
                    showMessage(`注册失败: ${data.detail}`, 'error');
                }
            } catch (error) {
                showMessage(`注册失败: ${error.message}`, 'error');
            }
        }

        // 用户登录
        async function loginUser() {
            const username = document.getElementById('loginUsername').value;
            const password = document.getElementById('loginPassword').value;

            if (!username || !password) {
                showMessage('请填写用户名和密码', 'error');
                return;
            }

            try {
                const response = await fetch(`${API_BASE}/UserLogin`, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify({
                        username,
                        password
                    })
                });

                const data = await response.json();

                if (response.ok) {
                    showMessage(`登录成功！欢迎 ${data.username}`);
                    clearForm('login');
                } else {
                    showMessage(`登录失败: ${data.detail}`, 'error');
                }
            } catch (error) {
                showMessage(`登录失败: ${error.message}`, 'error');
            }
        }

        // 更新用户
        async function updateUser() {
            const userId = document.getElementById('userId').value;
            const newPhone = document.getElementById('newPhone').value;
            const newEmail = document.getElementById('newEmail').value;

            if (!userId) {
                showMessage('请输入用户ID', 'error');
                return;
            }

            if (!newPhone && !newEmail) {
                showMessage('请至少输入一个新手机号或新邮箱', 'error');
                return;
            }

            try {
                const params = new URLSearchParams();
                if (newPhone) params.append('phone', newPhone);
                if (newEmail) params.append('email', newEmail);

                const response = await fetch(`${API_BASE}/users/${userId}?${params}`, {
                    method: 'PUT'
                });

                const data = await response.json();

                if (response.ok) {
                    showMessage('用户更新成功！');
                    clearForm('update');
                    loadUsers();
                } else {
                    showMessage(`更新失败: ${data.detail}`, 'error');
                }
            } catch (error) {
                showMessage(`更新失败: ${error.message}`, 'error');
            }
        }

        // 删除用户
        async function deleteUser() {
            const userId = document.getElementById('userId').value;

            if (!userId) {
                showMessage('请输入用户ID', 'error');
                return;
            }

            if (!confirm('确定要删除这个用户吗？')) {
                return;
            }

            try {
                const response = await fetch(`${API_BASE}/users/${userId}`, {
                    method: 'DELETE'
                });

                if (response.ok) {
                    showMessage('用户删除成功！');
                    clearForm('update');
                    loadUsers();
                } else {
                    const data = await response.json();
                    showMessage(`删除失败: ${data.detail}`, 'error');
                }
            } catch (error) {
                showMessage(`删除失败: ${error.message}`, 'error');
            }
        }

        // 加载用户列表
        async function loadUsers() {
            const tableDiv = document.getElementById('userTable');
            tableDiv.innerHTML = '<div class="loading">加载中...</div>';

            try {
                const response = await fetch(`${API_BASE}/users/`);
                const users = await response.json();

                if (response.ok) {
                    displayUsers(users);
                    // 加载用户列表后自动刷新全局统计
                    refreshGlobalStats();
                } else {
                    showMessage(`加载用户列表失败: ${users.detail}`, 'error');
                }
            } catch (error) {
                showMessage(`加载用户列表失败: ${error.message}`, 'error');
            }
        }

        // 搜索用户
        async function searchUsers() {
            const searchTerm = document.getElementById('searchInput').value.toLowerCase();
            const tableDiv = document.getElementById('userTable');
            
            if (!searchTerm) {
                loadUsers();
                return;
            }

            tableDiv.innerHTML = '<div class="loading">搜索中...</div>';

            try {
                const response = await fetch(`${API_BASE}/users/`);
                const users = await response.json();

                if (response.ok) {
                    const filteredUsers = users.filter(user => 
                        user.username.toLowerCase().includes(searchTerm) ||
                        user.phone.includes(searchTerm) ||
                        user.email.toLowerCase().includes(searchTerm)
                    );
                    displayUsers(filteredUsers);
                } else {
                    showMessage(`搜索失败: ${users.detail}`, 'error');
                }
            } catch (error) {
                showMessage(`搜索失败: ${error.message}`, 'error');
            }
        }

        // 显示用户列表
        function displayUsers(users) {
            const tableDiv = document.getElementById('userTable');
            
            if (users.length === 0) {
                tableDiv.innerHTML = '<div class="loading">没有找到用户</div>';
                return;
            }

            let tableHTML = `
                <table>
                    <thead>
                        <tr>
                            <th>ID</th>
                            <th>用户名</th>
                            <th>手机号</th>
                            <th>邮箱</th>
                            <th>注册时间</th>
                            <th>操作</th>
                        </tr>
                    </thead>
                    <tbody>
            `;

            users.forEach(user => {
                const createdDate = user.created_at ? new Date(user.created_at).toLocaleString('zh-CN') : '未知';
                tableHTML += `
                    <tr>
                        <td>${user.id}</td>
                        <td>${user.username}</td>
                        <td>${user.phone}</td>
                        <td>${user.email}</td>
                        <td>${createdDate}</td>
                        <td>
                            <button class="stats-btn" onclick="showUserStats(${user.id}, '${user.username}')">
                                数据统计
                            </button>
                        </td>
                    </tr>
                `;
            });

            tableHTML += '</tbody></table>';
            tableDiv.innerHTML = tableHTML;
        }

        // 清空表单
        function clearForm(type) {
            if (type === 'register') {
                document.getElementById('username').value = '';
                document.getElementById('phone').value = '';
                document.getElementById('email').value = '';
                document.getElementById('password').value = '';
            } else if (type === 'login') {
                document.getElementById('loginUsername').value = '';
                document.getElementById('loginPassword').value = '';
            } else if (type === 'update') {
                document.getElementById('userId').value = '';
                document.getElementById('newPhone').value = '';
                document.getElementById('newEmail').value = '';
            }
        }

        // 页面加载时获取用户列表
        window.onload = function() {
            loadUsers();
        };

        // 搜索框回车事件
        document.getElementById('searchInput').addEventListener('keypress', function(e) {
            if (e.key === 'Enter') {
                searchUsers();
            }
        });

        // 显示用户统计模态框
        function showUserStats(userId, username) {
            document.getElementById('statsModalTitle').textContent = `${username} 的数据统计`;
            document.getElementById('statsModal').style.display = 'block';
            loadUserStats(userId);
        }

        // 关闭统计模态框
        function closeStatsModal() {
            document.getElementById('statsModal').style.display = 'none';
        }

        // 点击模态框外部关闭
        window.onclick = function(event) {
            const modal = document.getElementById('statsModal');
            if (event.target === modal) {
                closeStatsModal();
            }
        }

        // 加载用户统计数据
        async function loadUserStats(userId) {
            const statsContent = document.getElementById('statsContent');
            statsContent.innerHTML = '<div class="stats-loading">加载统计数据中...</div>';

            try {
                // 获取今日统计
                const todayResponse = await fetch(`http://127.0.0.1:8000/api/stats/user/${userId}/today`);
                const todayStats = await todayResponse.json();

                // 获取月度统计
                const currentDate = new Date();
                const year = currentDate.getFullYear();
                const month = currentDate.getMonth() + 1;
                const monthResponse = await fetch(`http://127.0.0.1:8000/api/stats/user/${userId}/month/${year}/${month}`);
                const monthStats = await monthResponse.json();

                // 获取所有统计
                const allResponse = await fetch(`http://127.0.0.1:8000/api/stats/user/${userId}`);
                const allStats = await allResponse.json();

                displayUserStats(todayStats, monthStats, allStats);
            } catch (error) {
                statsContent.innerHTML = `
                    <div class="stats-error">
                        加载统计数据失败: ${error.message}
                    </div>
                `;
            }
        }

        // 显示用户统计数据
        function displayUserStats(todayStats, monthStats, allStats) {
            const statsContent = document.getElementById('statsContent');
            
            // 计算月度总计
            const monthlyTTS = monthStats.reduce((sum, day) => sum + day.tts_count, 0);
            const monthlyASR = monthStats.reduce((sum, day) => sum + day.asr_seconds, 0);
            
            // 计算总计
            const totalTTS = allStats.reduce((sum, day) => sum + day.tts_count, 0);
            const totalASR = allStats.reduce((sum, day) => sum + day.asr_seconds, 0);

            statsContent.innerHTML = `
                <!-- 统计概览卡片 -->
                <div class="stats-summary">
                    <div class="stats-card">
                        <h3>今日TTS使用</h3>
                        <div class="value">${todayStats.tts_count || 0}</div>
                        <div class="unit">字符</div>
                    </div>
                    <div class="stats-card">
                        <h3>今日ASR使用</h3>
                        <div class="value">${todayStats.asr_seconds || 0}</div>
                        <div class="unit">秒</div>
                    </div>
                    <div class="stats-card">
                        <h3>本月TTS总计</h3>
                        <div class="value">${monthlyTTS}</div>
                        <div class="unit">字符</div>
                    </div>
                    <div class="stats-card">
                        <h3>本月ASR总计</h3>
                        <div class="value">${monthlyASR}</div>
                        <div class="unit">秒</div>
                    </div>
                    <div class="stats-card">
                        <h3>总TTS使用</h3>
                        <div class="value">${totalTTS}</div>
                        <div class="unit">字符</div>
                    </div>
                    <div class="stats-card">
                        <h3>总ASR使用</h3>
                        <div class="value">${totalASR}</div>
                        <div class="unit">秒</div>
                    </div>
                </div>

                <!-- 本月使用趋势 -->
                <div class="stats-chart">
                    <h3>本月使用趋势</h3>
                    ${monthStats.length > 0 ? `
                        <table class="stats-table">
                            <thead>
                                <tr>
                                    <th>日期</th>
                                    <th>TTS字符数</th>
                                    <th>ASR秒数</th>
                                </tr>
                            </thead>
                            <tbody>
                                ${monthStats.map(day => `
                                    <tr>
                                        <td>${day.date}</td>
                                        <td>${day.tts_count}</td>
                                        <td>${day.asr_seconds}</td>
                                    </tr>
                                `).join('')}
                            </tbody>
                        </table>
                    ` : '<p>本月暂无使用数据</p>'}
                </div>

                <!-- 所有历史数据 -->
                <div class="stats-chart">
                    <h3>所有历史数据</h3>
                    ${allStats.length > 0 ? `
                        <table class="stats-table">
                            <thead>
                                <tr>
                                    <th>日期</th>
                                    <th>TTS字符数</th>
                                    <th>ASR秒数</th>
                                </tr>
                            </thead>
                            <tbody>
                                ${allStats.slice(0, 20).map(day => `
                                    <tr>
                                        <td>${day.date}</td>
                                        <td>${day.tts_count}</td>
                                        <td>${day.asr_seconds}</td>
                                    </tr>
                                `).join('')}
                            </tbody>
                        </table>
                        ${allStats.length > 20 ? `<p style="text-align: center; color: #666; margin-top: 10px;">显示最近20条记录，共${allStats.length}条</p>` : ''}
                    ` : '<p>暂无历史使用数据</p>'}
                </div>
            `;
        }

        // 刷新全局统计数据
        async function refreshGlobalStats() {
            const todayTotalTTS = document.getElementById('todayTotalTTS');
            const todayTotalASR = document.getElementById('todayTotalASR');
            const monthTotalTTS = document.getElementById('monthTotalTTS');
            const monthTotalASR = document.getElementById('monthTotalASR');
            const allTotalTTS = document.getElementById('allTotalTTS');
            const allTotalASR = document.getElementById('allTotalASR');

            todayTotalTTS.textContent = '加载中...';
            todayTotalASR.textContent = '加载中...';
            monthTotalTTS.textContent = '加载中...';
            monthTotalASR.textContent = '加载中...';
            allTotalTTS.textContent = '加载中...';
            allTotalASR.textContent = '加载中...';

            try {
                // 获取今日全局统计
                const todayResponse = await fetch(`http://127.0.0.1:8000/api/stats/global/today`);
                const todayData = await todayResponse.json();
                todayTotalTTS.textContent = todayData.tts_count || 0;
                todayTotalASR.textContent = todayData.asr_seconds || 0;

                // 获取本月全局统计
                const currentDate = new Date();
                const year = currentDate.getFullYear();
                const month = currentDate.getMonth() + 1;
                const monthResponse = await fetch(`http://127.0.0.1:8000/api/stats/global/month/${year}/${month}`);
                const monthData = await monthResponse.json();
                monthTotalTTS.textContent = monthData.tts_count || 0;
                monthTotalASR.textContent = monthData.asr_seconds || 0;

                // 获取所有全局统计
                const allResponse = await fetch(`http://127.0.0.1:8000/api/stats/global`);
                const allData = await allResponse.json();
                allTotalTTS.textContent = allData.tts_count || 0;
                allTotalASR.textContent = allData.asr_seconds || 0;

                showMessage('全局统计已刷新！');
            } catch (error) {
                showMessage(`刷新全局统计失败: ${error.message}`, 'error');
                // 如果API不存在，显示默认值
                todayTotalTTS.textContent = '0';
                todayTotalASR.textContent = '0';
                monthTotalTTS.textContent = '0';
                monthTotalASR.textContent = '0';
                allTotalTTS.textContent = '0';
                allTotalASR.textContent = '0';
            }
        }
    </script>
</body>
</html>